<?php
class Mozg_Property_Validator
{
	private $_data;

	//fields error messages array(fieldName => message, ...);
	protected $_errorMessages = array();

	private $_errorFields = array();

	public function __construct(Mozg_Property_Params $data)
	{
		$this->_data = $data;
	}

	protected function GetData()
	{
		return $this->_data;
	}

	protected function AddErrorField($fieldName, $lang = false)
	{
		if (false !== $lang)
		{
			$this->_errorFields[$fieldName][$lang] = $this->GetErrorMessage($fieldName);
		}
		else
		{
			$this->_errorFields[$fieldName] = $this->GetErrorMessage($fieldName);
		}
	}

	protected function GetErrorMessage($fieldName)
	{
		if (isset($this->_errorMessages[$fieldName]))
		{
			$message = $this->_errorMessages[$fieldName];
		}
		else
		{
			$message = Mozg_Lang::_('Invalid');
		}

		return $message;
	}

	protected function SetErrorMessage($fieldName, $message)
	{
		$this->_errorMessages[$fieldName] = $message;
	}

	public function SetError($fieldName, $message = false, $lang = false)
	{
		$this->SetErrorMessage($fieldName, $message);
		$this->AddErrorField($fieldName, $lang);
		$this->SetState(false);
	}

	private function ClearErrors()
	{
		$this->_errorFields = array();
	}

	public function Validate()
	{
		$this->ClearErrors();

		//get set fields
		$fieldNames = array_keys($this->_data->ExportData());

		//merge with config fields
		$fieldNames = array_unique(array_merge($fieldNames, $this->_data->Config()->GetFields()));

		foreach ($fieldNames as $fieldName)
		{
			$validateMethod = 'Validate' .$fieldName;
			if (!method_exists($this, $validateMethod)) continue;

			$isMultiLang = $this->_data->Config()->IsMultilangField($fieldName);
			if ($isMultiLang)
			{
				foreach (Mozg_Lang::$langs as $lang)
				{
					$fieldValue = $this->_data->{'Get' .$fieldName}($lang);
					if (!$this->$validateMethod($fieldValue, $lang))
					{
						$this->AddErrorField($fieldName, $lang);
					}
				}
			}
			else
			{
				$fieldValue = $this->_data->{'Get' .$fieldName}($lang);
				if (!$this->$validateMethod($fieldValue))
				{
					$this->AddErrorField($fieldName);
				}
			}
		}

		$isValid = !sizeof($this->_errorFields);
		$this->SetState($isValid);

		return $isValid;
	}

	private function SetState($state)
	{
		$this->_state = (bool)$state;
	}

	public function GetState()
	{
		return $this->_state;
	}

	public function GetError($fieldName, $lang = false)
	{
		if (!isset($this->_errorFields[$fieldName])) return false;

		if (strlen($lang))
		{
			return isset($this->_errorFields[$fieldName][$lang]) ? $this->_errorFields[$fieldName][$lang] : false;
		}
		else
		{
			return $this->_errorFields[$fieldName];
		}
	}

	public function GetErrors()
	{
		return $this->_errorFields;
	}
}